<script setup>
import { onMounted, ref } from "vue";
import * as echarts from 'echarts/core';
import { PieChart } from "echarts/charts";
import { TitleComponent, TooltipComponent, VisualMapComponent } from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
import OrderApi from "@/api/order.js";

// 1. 注册 ECharts 必要组件（不变）
echarts.use([
  PieChart,
  TitleComponent,
  TooltipComponent,
  VisualMapComponent,
  CanvasRenderer
]);

// 2. 状态与引用管理（不变）
const chartRef = ref(null);
let chartInstance = null;
const isLoading = ref(true);
const errorMsg = ref('');

onMounted(async () => {
  try {
    isLoading.value = true;
    errorMsg.value = '';

    const chartData = await OrderApi.getOrderCount();

    if (chartRef.value) {
      if (chartInstance) chartInstance.dispose();
      chartInstance = echarts.init(chartRef.value);

      const option = {
        backgroundColor: '#099ddc', // 你的蓝色背景不变
        title: {
          text: '订单状态分布',
          left: 'center',
          top: 20,
          textStyle: { color: '#ccc', fontSize: 16 }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} 单 ({d}%)'
        },
        visualMap: {
          show: false,
          min: 0,
          max: 20,
          inRange: { colorLightness: [0, 1] }
        },
        series: [
          {
            name: '订单数量',
            type: 'pie',
            radius: ['30%', '60%'],
            center: ['50%', '50%'],
            data: chartData.sort((a, b) => a.value - b.value), // 数据逻辑不变
            roseType: 'radius',
            label: {
              color: 'rgb(248,248,248)',
              fontSize: 12,
              formatter: '{b}: {c}'
            },
            labelLine: {
              lineStyle: { color: 'rgba(246,7,7,0.3)' }, // 保持你的标签线颜色
              smooth: 0.2,
              length: 8,
              length2: 15
            },
            itemStyle: {
              // 👇 仅修改这里的颜色值，其他配置完全不变
              color: (params) => {
                const colorMap = {
                  '待支付': '#ff4d6d',    // 柔和玫瑰红（替换原#ff0202，不刺眼）
                  '待发货': '#ffb703',    // 暖橙色（保留橙色系，更协调）
                  '待收货': '#38b000',    // 鲜亮绿（与蓝色背景区分度高）
                  '已完成': '#7b2cbf'     // 深紫（避免与其他颜色冲突）
                };
                return colorMap[params.name] || '#c23531'; // 默认色不变
              },
              shadowBlur: 15,
              shadowColor: 'rgba(189,151,53,0.4)' // 保持你原有的阴影颜色
            },
            animationType: 'scale',
            animationEasing: 'elasticOut',
          }
        ]
      };

      chartInstance.setOption(option);
      const handleResize = () => chartInstance.resize();
      window.addEventListener('resize', handleResize);

      return () => {
        window.removeEventListener('resize', handleResize);
        chartInstance.dispose();
      };
    }
  } catch (error) {
    console.error('图表加载失败:', error);
    errorMsg.value = error.message || '订单状态图表加载失败，请稍后重试';
  } finally {
    isLoading.value = false;
  }
});
</script>

<template>
  <!-- 模板完全不变 -->
  <div class="chart-wrapper">
    <div ref="chartRef" class="chart-container" v-if="!errorMsg"></div>
    <div class="loading-state" v-if="isLoading && !errorMsg">
      <div class="spinner"></div>
      <p>加载订单状态数据中...</p>
    </div>
    <div class="error-state" v-if="errorMsg">
      <p>{{ errorMsg }}</p>
      <button @click="onMounted()">重新加载</button>
    </div>
  </div>
</template>

<style scoped>
/* 样式完全不变，保留你的原有配置 */
.chart-wrapper {
  position: relative;
  width: 100%;
  height: 450px;
  min-width: 300px;
  margin: 0 auto;
}

.chart-container {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.loading-state {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(63, 105, 152, 0.9);
  color: #ccc;
  border-radius: 8px;
}

.spinner {
  width: 36px;
  height: 36px;
  border: 3px solid rgba(105, 170, 63, 0.27);
  border-top-color: #1efad9;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-state {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgb(192, 160, 167);
  color: #ff4d4f;
  padding: 20px;
  text-align: center;
  border-radius: 8px;
}

.error-state button {
  margin-top: 16px;
  padding: 6px 16px;
  background-color: #1890ff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.error-state button:hover {
  background-color: #096dd9;
}
</style>